<template>
	<page-meta :page-style="'overflow:'+(pageMetaShow?'hidden':'visible')"></page-meta>
	<view class="content1">
		<image src="/static/package/bgIcon.png" class="bgIcon bgIcon1" mode="widthFix"></image>
		<image src="/static/package/bgIcon.png" class="bgIcon bgIcon2" mode="widthFix"></image>
		<image src="/static/package/bgIcon.png" class="bgIcon bgIcon3" mode="widthFix"></image>
		<view class="main" :style="{paddingTop: titleTop + 'px'}">

			<view class="mainHeader" :style="{minHeight: statusBarHeight+'px'}">
				<view class="waitingLay">
					<waiting></waiting>
				</view>
				<view class="toplay">
					<image class="titleImg" src="/static/package/titleImg.png" mode="widthFix"></image>

				</view>
			</view>
			<view class="headerSearch">
				<view class="searchBox">
					<!-- <uni-icons type="search" color="#fff" size="20"></uni-icons>
					<input type="text" v-model.trim="keyword" confirm-type="search" /> -->
					<uni-easyinput trim="all" :styles="styles" :placeholderStyle="placeholderStyle"
						primaryColor="#FF9BA7" placeholder="搜索我的关注" v-model="keyword" prefixIcon="search"
						confirmType="search" @confirm="resetList" @blur="resetList" @clear="resetList">

					</uni-easyinput>
				</view>
				<image class="searchIcon" src="/static/package/tipIcon.png" mode="widthFix" @click="Toggle"></image>
				<image class="searchIcon" src="/static/package/refreshIcon.png" mode="widthFix" @click="resetList">
				</image>

			</view>
			<view class="userBox">
				<!-- <view class="bgImg"> -->
				<image src="/static/package/userBg.png" class="userBg" mode="widthFix"></image>

				<!-- </view> -->
				<view class="userInfo">
					<image :src="userinfo.avatar||''" mode="aspectFill" class="userImg"></image>
					<view class="infoTxt">
						<view class="name">
							{{userinfo.nickname||''}}
						</view>
						<view class="idNumder">
							{{userinfo.qq||''}}
						</view>
					</view>
				</view>
			</view>
			<view class="options">
				<view :class="index==optionIndex?'option action':'option'" @click="optionIndexFn(index)"
					v-for="(item,index) in option" :key="index">
					{{item.name}}
				</view>
			</view>
			<scroll-view style="height: 1050rpx;position: relative;
		z-index: 3; background: #fff;" :scroll-top="scrollTop" scroll-y="true" refresher-enabled="true" @scroll="scroll"
				:refresher-triggered="triggered" :refresher-threshold="100" refresher-background="#fff"
				@refresherpulling="onPulling" @refresherrefresh="onRefresh" @refresherrestore="onRestore"
				@refresherabort="onAbort" @scrolltolower="scrolltolower">
				<noData v-if="list.length === 0 && !loading"></noData>
				<template v-else>
					<view class="cardLay">
						<view class="cardItem" v-for="(item,index) in list" :key="index">
							<cardBag :cardData="item" :urlKey="'image_url'" @imgClick="imgClickFn">
								<!-- @imgClick="item.is_expired!=1?downloadImage(item):''"> -->
								<template #option v-if="item.is_expired!=1">
									<view class="optionLay" @click="toggleSelection(item)">
										<uni-icons class="optionIcon"
											:type="isSelected(item.id)?'checkbox-filled':'circle'" color="#fff"
											size="14"></uni-icons>
									</view>
								</template>
								<template #infoMore>
									<view class="infoLay">
										<view class="infoTag">
											<template>
												<!-- "is_expired": 0//是否过期 -->
												<template v-if="item.is_expired!=1">
													<view v-if="item.product_status==0" class="tag"
														style="background-color: #FFE9C9;color: #FF984C;">
														{{item.product_status_text}}
													</view>
													<template v-if="item.product_status==1">
														<view v-if="item.receive_status==0" class="tag"
															style="background-color: #C9F6FF;color: #00AAB9;">
															{{item.receive_status_text}}
														</view>
														<view v-if="item.receive_status==1" class="tag"
															style="background-color: #C5FFDA;color: #00B451;">
															{{item.receive_status_text}}
														</view>
													</template>
												</template>
												<view v-else class="tag"
													style="background-color: #EDEDED;color: #999999;">已过期</view>
												<!-- <view v-if="item.status==4" class="tag"
													style="background-color:#C0D8FF ;color: #1E4DDA;">未在群</view>
												<view v-if="item.status==5" class="tag"
													style="background-color:#FFCDCD ;color: #FF5858;">已封禁</view>
												
												<view v-if="item.status==7" class="tag"
													style="background-color: #FFDE81;color: #9D740A;">卡门槛</view> -->
											</template>
											<view class="date">{{item.create_time|dateFilter}}</view>
										</view>
										<view class="shopInfo"
											@click="linkUrl('/pages/index/storeDetails?shopId='+item.shop_id)">
											<image class="logo" :src="item.shop_avatar" mode="aspectFit"></image>
											<view class="title">
												<view>{{item.shop_name}}</view>
												<uni-icons type="right" color="#5A5A5A" size="8"></uni-icons>
											</view>
										</view>
									</view>
								</template>
							</cardBag>
						</view>
					</view>
					<uni-load-more :status="loading ? 'loading' : noMoreData ? 'noMore' : 'more'"
						iconType="auto"></uni-load-more>
				</template>
			</scroll-view>
		</view>
		<uni-popup ref="popup" @change="changePopup" safeArea backgroundColor="#fff" borderRadius="38px 38px 0 0">
			<view class="shareContent">
				<view class="titleLay">
					<view class="title">
						背包说明
					</view>
					<view class="clearBox" @click="closePop">
						<uni-icons type="closeempty" color="#999999" size="16"></uni-icons>
					</view>
				</view>
				<view class="infoTxt">
					{{announcement}}
				</view>
			</view>
		</uni-popup>
		<view class="downBnt"><!-- downloadSelected -->
			<button class="btn" @click="receiveBackpackImage" :disabled="selectedItems.length === 0 || isDownloading">
				{{ isDownloading ? `下载中...${ currentDownloadIndex }/${ selectedItems.length }` : `下载已选·${selectedItems.length}`}}
			</button>
		</view>
		<tabbar :current="currentTab"></tabbar>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				styles: {
					backgroundColor: "rgba(255, 255, 255, 0.3)",
					color: '#fff',
					borderColor: 'rgba(255, 255, 255, 0.3)',
				},
				placeholderStyle: "color:#fff;font-size:21rpx",
				currentTab: 1,
				pageMetaShow: false,
				list: [],
				option: [{
					name: '全部',

				}, {
					name: '未领取',

				}],
				announcement: '',
				userinfo: {},
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				triggered: false,
				_freshing: false,
				optionIndex: 0,
				page: 1, // 当前页码
				page_size: 12, // 每页数量
				total: 0, // 总数据量
				loading: false, // 是否正在加载
				noMoreData: false, // 是否没有更多数据
				keyword: '',
				receive_status: undefined, //0|1,领取状态(0未领取/1已领取)
				selectedItems: [],
				selectedIds: [],
				// 下载用到的参数
				selectedItems: [],
				isDownloading: false,
				currentDownloadIndex: 0,
				downloadStatus: []
			}
		},
		filters: {
			dateFilter(val) {
				if (!val) {
					return
				} else {
					return val.substring(0, 10);
				}
			}
		},
		computed: {
			overallProgress() {
				if (this.selectedItems.length === 0) return 0;
				return (this.currentDownloadIndex / this.selectedItems.length) * 100;
			},
			selectedMap() {
				const map = {};
				this.selectedIds.forEach(id => {
					map[id] = true;
				});
				return map;
			},
			/* isMaxReached() {
				return this.selectedIds.length >= this.maxSelectCount;
			} */
		},
		onLoad() {
			this.getPackageFn();
			this.getBackpackAnnouncementFn();
			this._freshing = false;
		},
		async onShow() {
			await this.$onLaunched;
			this.userinfo = uni.getStorageSync('userInfo') || {};
		},
		// onShareAppMessage(res) {
		// 	return {
		// 		title: "给你分享了一份宝藏，快进来看看～",
		// 		path: '/pages/index/index',
		// 		imageUrl: '../../static/share.png'
		// 	};
		// },
		methods: {
			linkUrl(url) {
				uni.navigateTo({
					url
				})
			},
			changePopup(e) {
				this.pageMetaShow = e.show
			},
			optionFN(item) {
				item.action = !item.action
			},
			closePop() {
				this.$refs.popup.close()
			},
			Toggle() {
				this.$refs.popup.open('bottom')
			},
			optionIndexFn(index) {
				this.optionIndex = index
				if (index == 0) {
					// 全部
					// this.keyword=undefined;
					this.receive_status = undefined;
					this.resetList();
				} else {
					this.receive_status = 0;
					this.resetList();
				}
			},
			//自定义下拉刷新控件被下拉	
			onPulling(e) {
				// console.log("onpulling", e);
				// this.page = 1;
				// this.noMoreData = false;
				// this.getPackageFn();
			},
			// 自定义下拉刷新被触发	
			onRefresh() {
				console.log("onRefresh");
				let that = this;
				if (this._freshing) return;
				// 1. 设置刷新状态
				this._freshing = true;
				this.triggered = true;
				// 2. 重置分页参数
				// 3. 重新加载数据
				this.resetList();
				// 4. 无论成功失败，2秒后复位刷新状态
				setTimeout(() => {
					this.triggered = false;
					this._freshing = false;
				}, 3000);
			},
			// 自定义下拉刷新被复位	
			onRestore() {
				this.triggered = false;
				this._freshing = false;
				// this.triggered = false // 'restore'; // 需要重置
				console.log("onRestore");
			},
			// 自定义下拉刷新被中止
			onAbort() {
				console.log("onAbort");
			},
			// 滚动到底部/右边，会触发 scrolltolower 事件	
			scrolltolower: function(e) {
				console.log(e);
				// 如果没有更多数据或正在加载，则返回
				if (this.noMoreData || this.loading) return

				// 页码增加并获取下一页数据
				this.page++
				this.getPackageFn()
			},
			scroll: function(e) {
				// console.log(e)
				this.old.scrollTop = e.detail.scrollTop
			},
			// 回到顶部，目前没用，感觉可以优化流程
			goTop: function(e) {
				// 解决view层不同步的问题
				this.scrollTop = this.old.scrollTop
				this.$nextTick(function() {
					this.scrollTop = 0
				});
				uni.showToast({
					icon: "none",
					title: "纵向滚动 scrollTop 值已被修改为 0"
				})
			},
			// 重置列表（用于下拉刷新）
			resetList() {
				this.page = 1
				this.noMoreData = false;
				this.selectedItems = [];
				this.selectedItems = [];
				this.getPackageFn()
			},
			// 背包列表
			getPackageFn() {
				// 防止重复请求
				if (this.loading) return;

				// 设置加载状态
				this.loading = true;
				// this.triggered = true;
				uni.showLoading({
					title: '加载中...'
				})
				try {
					this.$http('/v1/users/package', {
						page: this.page,
						page_size: this.page_size,
						keyword: this.keyword,
						receive_status: this.receive_status,
					}).then(res => {
						console.log(res);
						if (res.code === 0) {
							const data = res.data;
							// 如果是第一页，直接赋值
							if (this.page === 1) {
								this.list = data.items || []
							} else {
								// 后续页，合并数据
								this.list = [...this.list, ...(data.items || [])]
							}

							// 更新总数据量
							this.total = data.total || 0

							// 判断是否还有更多数据
							this.noMoreData = this.list.length >= this.total;
							// 把下拉状态复位
							this.triggered = false;
							this._freshing = false;
						} else {
							this.$showToast(res.msg)
						}
					})

				} catch (error) {
					console.error('请求失败:', error)
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					})
				} finally {
					// 重置加载状态
					this.loading = false
					uni.hideLoading();
				}
			},
			// 背包公告
			getBackpackAnnouncementFn() {
				this.$http('/v1/users/backpack-announcement', {}).then(res => {
					console.log(res, "背包公告");
					if (res.code === 0) {
						this.announcement = res.data.announcement;
					} else {
						this.$showToast(res.msg)
					}
				})
			},
			// 图片单击下载
			imgClickFn(item) {
				console.log(item, "123");
				if (this.isDownloading) {
					uni.showToast({
						title: `有图片正在下载...`,
						icon: 'none'
					});
					return;
				}
				this.$http('/v1/users/receive-backpack-image', {
					id: [item.id],
				}, 'post').then(res => {
					console.log(res, "receiveBackpackImage");
					if (res.code === 0) {
						if (item.is_expired != 1) {
							this.downloadImage(item);
						} else {
							uni.showToast({
								title: `该图已过期`,
								icon: 'none'
							});
							return;
						}
					} else {
						this.$showToast(res.msg)
					}
				})
			},
			// 多选
			toggleSelection(item) {
				// 在下载，就不能选择
				if (this.isDownloading) {
					uni.showToast({
						title: `有图片正在下载...`,
						icon: 'none'
					});
					return;
				}
				if (this.isSelected(item.id)) {
					this.selectedIds = this.selectedIds.filter(id => id !== item.id);
					this.selectedItems = this.selectedItems.filter(selectedItem => selectedItem.id !== item.id);
					// this.totalPriceFn();
					return;
				}

				// if (this.isMaxReached) {
				// 	uni.showToast({
				// 		title: `最多只能选择${this.maxSelectCount}个项目`,
				// 		icon: 'none'
				// 	});
				// 	return;
				// }

				this.selectedIds.push(item.id);
				this.selectedItems.push({
					...item
				});
				// this.totalPriceFn();
			},
			isSelected(id) {
				return !!this.selectedMap[id];
			},
			/* isDisabled(id) {
				return this.isMaxReached && !this.isSelected(id);
			}, */
			receiveBackpackImage() {
				if (this.selectedIds.length === 0) {
					uni.showToast({
						title: '请先选择要下载的图片',
						icon: 'none'
					});
					return;
				}
				this.$http('/v1/users/receive-backpack-image', {
					id: this.selectedIds,
				}, 'post').then(res => {
					console.log(res, "receiveBackpackImage");
					if (res.code === 0) {
						// this.announcement = res.data.announcement;
						this.downloadSelected()
					} else {
						this.$showToast(res.msg)
					}
				})
			},
			async downloadSelected() {
				console.log(111111);
				console.log(this.selectedIds, this.selectedItems);
				if (this.selectedItems.length === 0) {
					uni.showToast({
						title: '请先选择要下载的图片',
						icon: 'none'
					});
					return;
				}
				this.isDownloading = true;
				this.currentDownloadIndex = 0;
				this.downloadStatus = [];
				// 初始化下载状态
				this.selectedItems.forEach(image => {
					this.downloadStatus.push({
						id: image.id,
						name: image.image_name,
						progress: '等待下载'
					});
				});

				// 依次下载每张图片
				for (let i = 0; i < this.selectedItems.length; i++) {
					const image = this.selectedItems[i];
					this.currentDownloadIndex = i + 1;

					// 更新下载状态
					const statusIndex = this.downloadStatus.findIndex(s => s.id === image.id);
					if (statusIndex > -1) {
						this.downloadStatus[statusIndex].progress = '下载中...';
						// 强制更新视图
						this.$forceUpdate();
					}

					try {
						// 使用UniApp的下载API
						const result = await this.downloadImage(image);

						// 更新下载状态为成功
						if (statusIndex > -1) {
							this.downloadStatus[statusIndex].progress = '下载成功';
							this.$forceUpdate();
						}
					} catch (error) {
						// 更新下载状态为失败
						if (statusIndex > -1) {
							this.downloadStatus[statusIndex].progress = '下载失败';
							this.$forceUpdate();
						}
						console.error(`下载图片失败: ${image.image_name}`, error);
					}

					// 添加延迟，使进度显示更明显
					// await this.delay(500);
				}

				this.isDownloading = false;
				uni.showToast({
					title: '所有图片下载完成'
				});
			},
			downloadImage(image) {
				console.log(image);
				return new Promise((resolve, reject) => {
					uni.downloadFile({
						url: this.$options.filters.completeUrl(image.composite_image_url),
						success: (res) => {
							if (res.statusCode === 200) {
								// 下载成功，保存到相册
								uni.saveImageToPhotosAlbum({
									filePath: res.tempFilePath,
									success: () => {
										resolve(image);
									},
									fail: (err) => {
										reject(err);
									}
								});
							} else {
								reject(new Error('下载失败'));
							}
						},
						fail: (err) => {
							reject(err);
						}
					});
				});
			},

			// delay(ms) {
			// 	return new Promise(resolve => setTimeout(resolve, ms));
			// }
		}
	}
</script>
<style scoped>
	page {}
</style>
<style lang="scss" scoped>
	.content1 {
		position: relative;
		min-height: 100vh;
		background: linear-gradient(180deg, #FCCEDB 0%, rgba(255, 255, 255, 0) 100%);

		.bgIcon {
			@include setwh(200upx, 0);
			position: fixed;
			top: 0;
			opacity: 0.38;
		}

		.bgIcon1 {
			top: -52rpx;
			left: -48rpx;
		}

		.bgIcon2 {
			left: 90rpx;
		}

		.bgIcon3 {
			top: 110rpx;
		}

		.main {
			// padding-bottom: 100upx;
		}

		.mainHeader {
			position: relative;

			::v-deep .waitingLay {
				position: absolute;
				padding-left: 36upx;
				min-width: 192upx;
				bottom: 0;

				.loadingNum {
					font-size: 15rpx;
					color: #FF9999;

					text {
						color: #FF6A20;
						font-size: 26rpx;
					}
				}
			}

			.titleImg {
				position: fixed;
				left: 50%;
				transform: translateX(-50%);
				@include setwh(264upx, 0);
				// margin: 0 auto;
			}

			.toplay {
				position: relative;

			}
		}

		.headerSearch {
			@include flexLayout(center, space-between);
			margin-top: 14upx;
			padding: 0 22upx;

			.searchBox {
				@include flexLayout(center);
				width: 534rpx;
				height: 74rpx;

				// padding-left: 34upx;
				// background: rgba(255, 255, 255, 0.3);
				// margin: 0 auto 56upx;
				::v-deep .uni-easyinput {
					.uni-icons {
						color: #FFFFFF !important;
					}

					.is-input-border {
						border-radius: 38upx;
						backdrop-filter: blur(16px);
						box-shadow: 0rpx 4rpx 8rpx 0rpx rgba(173, 173, 173, 0.5);

						// height: 70upx;
						.uni-easyinput__content-input {
							// padding-left: 30px;
							height: 74upx;

						}
					}
				}

				/* .is-input-border {
					border-radius: 30upx;
				}
				
				.uni-easyinput__content-input {
					height: 74upx;
				} */
				/* input {
					width: 80%;
					padding-left: 20upx;
					color: #fff;
				} */
			}

			.searchIcon {
				@include setwh(88upx, 0);
				// margin-right: 55upx;
			}
		}

		.options {
			@include flexLayout(center);
			margin: 42upx 0 0 0;
			padding: 34upx 50upx 50upx 34upx;
			// background: #FFFFFF;
			background: url("/static/package/packageTabBg3.png") no-repeat;
			background-size: cover;
			// box-shadow: 0rpx 4rpx 8rpx 0rpx rgba(0, 0, 0, 0.5);
			border-radius: 40upx 40upx 0 0;
			width: 100%;
			height: 132upx;
			position: relative;
			z-index: 2;

			// clip-path: polygon(0% 0%, 78% 0%, 96% 100%, 0% 100%);
			.option {
				font-family: AlimamaFangYuanTiVF;
				font-weight: bold;
				font-size: 34rpx;
				color: #8B8B8B;
				line-height: 42rpx;
				position: relative;
				z-index: 2;

				&:after {
					content: '';
					width: 0;
					height: 8rpx;
					background: none;
					border-radius: 4rpx;
					@include positionCenter;
					top: 54upx;
					transition: width .5s;
				}

				&+.option {
					margin-left: 60upx;
				}
			}

			.action {
				font-weight: bold;
				color: #000000;
				transition: color 1s 1s;
				transition-delay: 2s;
				transition: all 1s;

				&:after {
					content: '';
					background: linear-gradient(90deg, #FF85B8 0%, #FFC9AF 100%);
					width: 50rpx;
				}
			}
		}

		.userBox {
			position: relative;
			z-index: 1;

			// .bgImg{
			// position: relative;
			.userBg {
				position: absolute;
				top: 0;
				right: -16upx;
				width: 516upx;
				// }
			}

			.userInfo {
				@include flexLayout(center);
				position: absolute;
				@include setwh(356rpx, 124rpx);
				right: 0;
				top: 34rpx;

				.userImg {
					background-color: #F3F3F3;
					@include setwh(118upx, 118upx);
					border-radius: 50%;
				}

				.infoTxt {
					margin-left: 20upx;
					transform: rotate(-3deg);
					margin-top: 10upx;

					.name {
						font-family: SourceHanSansSC;
						font-weight: bold;
						font-size: 24rpx;
						color: #000000;
						margin-bottom: 10upx;
					}

					.idNumder {
						font-family: SourceHanSansSC;
						font-weight: 500;
						font-size: 20rpx;
						color: #A4A4A4;
					}
				}
			}
		}
	}

	.cardLay {
		padding: 0 0 40upx 20upx;
		@include flexLayout(center, flex-start);
		flex-wrap: wrap;
		column-gap: 10rpx;
		background: #FFFFFF;
		row-gap: 14upx;
		position: relative;
		z-index: 3;

		::v-deep .nodataLay {
			width: calc(100vw - 20upx);
		}

		::v-deep .cardItem {
			.optionLay {
				position: absolute;
				top: 0;
				left: 0;
				width: 40rpx;
				height: 32rpx;
				background: rgba(0, 0, 0, 0.43);
				border-radius: 0rpx 0rpx 10rpx 0rpx;

				.uni-icons {
					@include positionCenter;
					line-height: 1;
				}
			}

			.infoLay {
				.infoTag {
					@include flexLayout(center, space-between);
					margin: 12upx 0;

					.tag {
						font-family: SourceHanSansSC;
						width: 63rpx;
						height: 22rpx;
						border-radius: 4rpx;
						text-align: center;
						font-size: 14rpx;
						line-height: 22upx;
					}

					.date {
						font-family: SourceHanSansSC;
						font-weight: 500;
						font-size: 14rpx;
						color: #C8C8C8;
					}
				}

				.shopInfo {
					width: 100%;
					@include flexLayout(center, space-between);
					background: #FFF5F5;
					border-radius: 8rpx;
					padding: 4upx 10upx;

					.logo {
						@include setwh(28upx, 28upx);
						margin-right: 12upx;
						background-color: #666;
						border-radius: 50%;
					}

					.title {
						@include flexLayout(center, space-between);
						font-family: STHeitiSC, STHeitiSC;
						font-weight: 500;
						font-size: 16rpx;
						color: #5A5A5A;
						width: calc(100% - 40upx);

						view {
							width: 122upx;
							@include lineOver;
						}
					}
				}
			}
		}
	}

	.downBnt {
		position: fixed;
		left: 50%;
		transform: translateX(-50%);
		bottom: 200upx;
		z-index: 9;

		// background-color: rebeccapurple;
		.btn {
			width: 264rpx;
			height: 56rpx;
			background: linear-gradient(155deg, #FFE4EC 0%, #FE92B0 100%);
			border-radius: 30rpx;
			box-shadow: none;
			border: none;
			font-family: AlimamaFangYuanTiVF, AlimamaFangYuanTiVF;
			font-weight: bold;
			font-size: 26rpx;
			color: #FFFFFF;
			line-height: 56rpx;
		}
	}

	.shareContent {
		position: relative;
		z-index: 999;

		.titleLay {
			@include flexLayout(center,
				space-between);
			padding: 20upx 50upx 48upx;

			.title {
				font-family: SourceHanSansSC, SourceHanSansSC;
				font-weight: 400;
				font-size: 32rpx;
				color: #000000;
			}

			.clearBox {
				@include flexLayout(center, center);
				@include setwh(46upx, 46upx);
				background-color: #EDEDED;
				border-radius: 50%;

			}
		}

		.infoTxt {
			padding: 0 66upx;
			font-family: SourceHanSansSC, SourceHanSansSC;
			font-weight: 400;
			font-size: 29rpx;
			color: #454545;
			line-height: 40rpx;

			white-space: pre-line;

		}
	}
</style>